<?php
declare (strict_types=1);

namespace app\service;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use think\Exception;
use think\facade\Cache;
use think\facade\Log;

class GetWeatherInfo
{
    //+-------------------------------------------------------------------
    //|购买账号：jinglaikj
    //|文档地址：https://market.aliyun.com/apimarket/detail/cmapi00062493?accounttraceid=4a0fe2a8174345feb09a7c0e5bfcbad3rgvf#sku=yuncode5649300002
    //+-------------------------------------------------------------------
    protected $host = "https://getweather.market.alicloudapi.com";
    protected $appCode = '63c1b74ccd014e76a0b252f581f88a1e';

    public function __construct()
    {

    }

    public function getInfo($ip, $serialNumber = null)
    {
        try {
            if (!$ip) {
                throw new Exception('参数错误');
            }

            $cacheKey = hash('sha256', $ip);
            $cacheData = Cache::get($cacheKey);
            if ($cacheData) {
                return $cacheData;
            }

            $client = new Client(['base_uri' => $this->host]);
            $response = $client->request('GET', '/lundear/weather1d', [
                'headers' => [
                    'Authorization' => "APPCODE {$this->appCode}"
                ],
                'query' => [
                    'ip' => $ip
                ]
            ]);

            $responseBody = json_decode($response->getBody()->getContents(), true);
            Log::write("[weatherInfo]{$serialNumber}:" . var_export($responseBody, true));
            $temperature = $responseBody['data']['day']['temperature'] ?? 0;
            Cache::set($cacheKey, $temperature, 7200);

            return $temperature;
        } catch (\Exception|GuzzleException $e) {
            return null;
        }
    }
}
